<title>XSocial gree</title>
<script type="text/javascript" src="<?php echo $this->webRoot ?>js/xsocialRpc.js"></script>
<script type="text/javascript" src="http://pf-sb.gree.jp/js/app/touch.js"></script>
<script>
//set correct value for xsocialApi.owner,xsocialApi.friends
//do authencation with sig = md5(sessionkey + uid + secretkey)
//put sessionkey,uid,sig in url GET parameters
//implement method like invite(),adjustHeight(),post(),payment()
//then call initRpc();
</script>
<?php
require_once('lib/gree_OAuth/GreeAPI.php');
$app_conf = array(
	'consumer_key' =>'ce8adee3b53a',
	'consumer_secret' =>'72eb65d830baca53979157179a5eb24c',
	'api.endpoint_url' =>'http://os-sb.gree.jp/api/rest',
);
$oauth_conf = $app_conf ;

// parse user request
$user_request = OAuthRequest::from_request(null, null, null);//???没有用到
$oauth_token          = $_REQUEST['oauth_token'];
$oauth_token_secret   = $_REQUEST['oauth_token_secret'];
$oauth_signature      = $_REQUEST['oauth_signature'];//???没有用到
$opensocial_viewer_id = $_REQUEST['opensocial_viewer_id'];
$xoauth_requestor_id  = $opensocial_viewer_id;

// api endpoint
$endpoint_url = $oauth_conf['api.endpoint_url'] . '/people/@me/@self/?fields=id,nickname,thumbnailUrl';
$friends_url    = $oauth_conf['api.endpoint_url'] . '/people/@me/@all/?fields=id,nickname,thumbnailUrl';
$activity_url   =  $oauth_conf['api.endpoint_url'] . '/activities/@me/@self/@app';

$http_method = 'GET';
 
// url query
$request_data = array();
$request_data['xoauth_requestor_id'] = $xoauth_requestor_id;
 
 //function getHeader( $http_method,$endpoint_url, $request_data){
// /*
// sign request
$signature_method = new OAuthSignatureMethod_HMAC_SHA1();
$oauth_consumer = new OAuthConsumer($oauth_conf['consumer_key'], $oauth_conf['consumer_secret']);
$access_token   = new OAuthToken($oauth_token, $oauth_token_secret);
//var_dump($access_token);

$signature_valid = $signature_method->check_signature($user_request, $oauth_consumer, 
    $access_token, $oauth_signature);
 //var_dump($signature_valid);
 /*
// print validation result
if ($signature_valid !== true) {
    header('HTTP/1.1 403 Forbidden');
} else {
    header("Content-type: text/html; charset=UTF-8");
    echo "validation OK <br />";
	die();
}
*/
//*/
//$gree = new GreeAPI($oauth_conf['consumer_key'],$oauth_conf['consumer_secret'],$oauth_token, $oauth_token_secret);

///*

/*
//个人信息验证 
$oauth_request = OAuthRequest::from_consumer_and_token($oauth_consumer, $access_token, $http_method, $endpoint_url, $request_data);
$oauth_request->sign_request($signature_method, $oauth_consumer, $access_token);
// get header
$authorization_header_string = $oauth_request->to_header();
$authorization_header = substr($authorization_header_string, strlen('Authorization:'));

//好友信息验证
$oauth_request2 = OAuthRequest::from_consumer_and_token($oauth_consumer, $access_token, $http_method, $friends_url, $request_data);
$oauth_request2->sign_request($signature_method, $oauth_consumer, $access_token);
// get header
$authorization_header_string2 = $oauth_request2->to_header();
$authorization_header2 = substr($authorization_header_string2, strlen('Authorization:'));
*/
$authorization_header= getAuthHeader($signature_method,$oauth_consumer,$access_token,'GET',$endpoint_url,$request_data);
$authorization_header2 = getAuthHeader($signature_method,$oauth_consumer,$access_token,'GET',$friends_url,$request_data);
$authorization_header3 = getAuthHeader($signature_method,$oauth_consumer,$access_token,'POST',$activity_url,$request_data);
/*
//feed信息验证
$oauth_request3 = OAuthRequest::from_consumer_and_token($oauth_consumer, $access_token, 'POST',  $activity_url, $request_data);

$oauth_request3->sign_request($signature_method, $oauth_consumer, $access_token);
// get header
$authorization_header_string3 = $oauth_request3->to_header();
$authorization_header3 = substr($authorization_header_string3, strlen('Authorization:'));
$authorization_header3 .=",xoauth_requestor_id=\"".$xoauth_requestor_id.'"';

*/
//var_dump($authorization_header3);die();
//*/
//$authorization_header = $gree->getOauthHeader($endpoint_url,$request_data);

//	return $authorization_header;
//}
//$authorization_header = getHeader($http_method,$friends_url, $request_data);
//var_dump($authorization_header);die();
function getAuthHeader($signature_method,$oauth_consumer,$access_token,$http_method,$url,$request_data){
	$oauth_request = OAuthRequest::from_consumer_and_token($oauth_consumer, $access_token, $http_method, $url, $request_data);
	$oauth_request->sign_request($signature_method, $oauth_consumer, $access_token);
	// get header
	$authorization_header_string = $oauth_request->to_header();
	$authorization_header = substr($authorization_header_string, strlen('Authorization:'));
	if($http_method == 'POST'){
		$authorization_header .=",xoauth_requestor_id=\"".$request_data['xoauth_requestor_id'].'"';
	}
	return $authorization_header;
}
function getRequest($endpoint_url,$xoauth_requestor_id,$authorization_header){
	$useragent = 'TalentWalker API PHP5 Client 1.0 (curl) ' . phpversion();
	if(function_exists('curl_init')){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $endpoint_url . '&xoauth_requestor_id=' .$xoauth_requestor_id);
		//curl_setopt($ch, CURLOPT_URL, $endpoint_url );
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		//curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ;
		curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
		curl_setopt($ch, CURLOPT_HTTPGET,true);
		curl_setopt($ch, CURLOPT_TIMEOUT, 10); //设置超时时间
		curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type:application/json','Authorization:'.$authorization_header));
		$response_body = curl_exec($ch);
		//var_dump(json_decode($response_body,true));die();
		$response_body = json_decode($response_body,true);
		curl_close($ch);
		return $response_body;
	}else{
		//$response_body = file_get_contents($endpoint_url);
		//header('HTTP/1.1 500 Internal Server Error');
		//echo "failed", "\n";
		//exit();
		return false;
	}
}
function postRequest($endpoint_url,$request_data,$authorization_header){
	//$useragent = 'TalentWalker API PHP5 Client 1.0 (curl) ' . phpversion();
	if(function_exists('curl_init')){
	try{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $endpoint_url);
		//curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
		//curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
		curl_setopt($ch, CURLOPT_POST,true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($request_data));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		//curl_setopt($ch, CURLOPT_TIMEOUT, 10); //设置超时时间
		curl_setopt($ch, CURLOPT_HEADER, true);
		//curl_setopt($ch, CURLOPT_HTTPHEADER,array('Authorization:'.$authorization_header));
		curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: application/json','Authorization:'.$authorization_header));
		$data = curl_exec($ch);
		$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

		$errno = curl_errno($ch);

		$error = curl_error($ch);
		curl_close($ch);
		if ($errno != CURLE_OK) {
		  throw new osapiException("HTTP Error: " . $error);
		}

		list($raw_response_headers, $response_body) = explode("\r\n\r\n", $data, 2);
		$response_header_lines = explode("\r\n", $raw_response_headers);
		array_shift($response_header_lines);
		$response_headers = array();
		foreach($response_header_lines as $header_line) {
		  list($header, $value) = explode(': ', $header_line, 2);
		  if (isset($response_header_array[$header])) {
			$response_header_array[$header] .= "\n" . $value;
		  } else {
			$response_header_array[$header] = $value;
		  }
		}
    $response_body = array('http_code' => $http_code, 'data' => $response_body, 'headers' => $response_header_array);

		}catch(Exception $e){
			var_dump($e);
		}
		//var_dump($response_body);die();
		//$response_body = json_decode($response_body,true);
		return $response_body;
	}else{
		//$response_body = file_get_contents($endpoint_url);
		//header('HTTP/1.1 500 Internal Server Error');
		//echo "failed", "\n";
		//exit();
		return false;
	}
}
//echo "<pre>";
$request_data = array();
$request_data['title'] ='login feed'; 
$request_data['url'] ='http://pf-sb.gree.jp/6120'; 
//echo json_encode($request_data);
//$activity_url = 'http://gree.farm.7talent.com/request.php';
$state = postRequest($activity_url,$request_data,$authorization_header3);
//var_dump($state);die();

$viewer = getRequest($endpoint_url,$xoauth_requestor_id,$authorization_header);
$friends = getRequest($friends_url,$xoauth_requestor_id,$authorization_header2);
//$viewer = $gree->curlRequest($endpoint_url,$xoauth_requestor_id,$authorization_header);
//$friends = $gree->curlRequest($endpoint_url,$xoauth_requestor_id,$authorization_header);
//var_dump($viewer);die();
//var_dump($friends);die();
if(empty($friends)){
 $friendsJson = '{
    "totalResults": 4,
    "itemsPerPage": 4,
    "entry": [
      {
        "nickname": "test1",
        "id": "7",
        "thumbnailUrl": "http://gree.jp/img/0123457.jpg"
      },
      {
        "nickname": "test2",
        "id": "8",
        "thumbnailUrl": "http://gree.jp/img/0123458.jpg"
      },
      {
        "nickname": "test3",
        "id":"9",
        "thumbnailUrl": "http://gree.jp/img/0123459.jpg"
      },
      {
        "nickname": "test4",
        "id": "60",
        "thumbnailUrl": "http://gree.jp/img/0123460.jpg"
      }
    ]
  }';
  $friends = json_decode($friendsJson,true);
  //var_dump($friends);die();
}
?>
<div id="gree_menu">
<a href="invite:friends?callbackfunc=my_invite_callback&body=test invite friends">invite friends js</a>
<a href="invite:friends?callbackurl=http%3A%2F%2Fbaidu.com%2F%3Fa%3D1%26b%3D2body=callback invite">invite friends callbackurl</a>
<a href="<?php echo $_SERVER['PHP_SELF']  ?>?action=feed">feed</a>
</div>
<div id="xsocial-container"></div>
<script type="text/javascript">
var xsocialTestApi = {
    init : function() {
        var viewer = <?php echo json_encode($viewer['entry'][0]) ?>;
        xsocialTestApi.viewer = viewer;
        xsocialTestApi.uid = viewer.id;
       // xsocialTestApi.sessionkey = <?php echo $sessionkey ?>;
       // xsocialTestApi.sig = "<?php echo $sig ?>";
        initRpc();
    },
    
    getViewer : function(callback) {
        if (callback) callback(xsocialTestApi.viewer);
    },
    
    getFriends : function(callback) {
        var friends = <?php echo json_encode($friends) ?>;
        
        if (callback) callback(friends);
    },
    invite : function(bundleData,callback) {
        alert("invite not implemented.");
    },
    payment : function() {
        alert("payment not implemented.");
    },
    adjustHeight : function() {
    },
    post : function(bundleData, callback) {
        //TODO: test bundleData fields  
        alert('post is not implemented');
    }
};

var xsocialApi = xsocialTestApi;

		greepf.callbackStore.register("my_invite_callback", function (response) {
		  // エラー判定
		  if (response.hadError()) {
			var errorCode = response.getErrorCode();
			var errorMessage = response.getErrorMessage();
			// エラー処理
			return;
		  }
		  // 招待ユーザーのID取得
		  var invitedUser = response.getData()['recipientIds'];
		  //alert(invitedUser);
		});

</script>
<script>
var ifrSrc = "<?php echo $this->appIframeUrl ?>";
xsocialApi.init();
</script>